﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Ms;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Applet.RequestDto;
using VisionCloud.Domain.DtoModel.Applet.ResponseDto;
using VisionCloud.Domain.Extension;
using VisionCloud.Domain.Repository.Interface.Ms;

namespace VisionCloud.Domain.Repository.Implement.Ms
{
    public class MsUserToProjectRepository : BaseRepository<MsUserToProject>, IMsUserToProjectRepository
    {
        /// <summary>
        /// 根据项目ID获取所有关联的用户Id和电话号码
        /// </summary>
        /// <returns></returns>
        public async Task<Dictionary<Guid, string>> GetRefUserPhonesByProjId(Guid projId)
        {
            var user = this.Db.SysUsers;
            var userToproj = this.Db.MsUserToProjects;
            var result = await user.Join(userToproj,
                                    x => x.YunUserGuid,
                                    y => y.YunUserGuid,
                                    (x, y) => new { x.PhoneNumber, x.YunUserGuid, y.YunProjectGuid })
                             .Where(a => a.YunProjectGuid == projId)
                             .GroupBy(b => new { b.YunUserGuid, b.PhoneNumber })
                             .Select(i => i.Key)
                             .ToDictionaryAsync(c => c.YunUserGuid, c => c.PhoneNumber);
            return result;
        }

        public async Task<List<ProjectLocationDto>> QueryProjectLocations(QueryProjectLocationDto query, Guid userId)
        {
            var list = await Db.MsProjects
                            .Join(Db.MsUserToProjects,
                                    x => x.ProjectId,
                                    y => y.YunProjectGuid,
                                    (x, y) => new { ProjectName = x.Name, x.ProjectId, x.Address, x.Latitude, x.Longitude, UserId = y.YunUserGuid, x.City, x.IsDeleted, x.IsCanPull, x.Town, x.PubliceDate, x.CompanyGuid })
                            .Where(a => a.UserId == userId
                            && !a.IsDeleted
                            && a.PubliceDate != null
                            && (query.Status == null || query.Status == a.IsCanPull)
                            && a.CompanyGuid == OperatorProvider.Get().CompanyGuid)
                            .WhereIf(!string.IsNullOrEmpty(query.City) && query.City != "全国", x => x.City == query.City)
                            .WhereIf(!string.IsNullOrWhiteSpace(query.QueryValue), s => s.ProjectName.Contains(query.QueryValue))
                            .Select(b => new ProjectLocationDto { Address = b.Address, ProjectId = b.ProjectId, ProjectName = b.ProjectName, Latitude = b.Latitude, Longitude = b.Longitude, CityTown = b.City + b.Town })
                            .ToListAsync();
            return list;
        }
    }
}